﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using NHibernate;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Data.Model;
using NHibernate.Transform;
using System.Collections;
using ZLCMS.Business.Util;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text;
using ZLCMS.Business.Common;
using System.Drawing.Imaging;
using System.Drawing;
using ZLCMS.Business.WeixinService.Data;
using ZLCMS.Business.WeixinService;
using ZLCMS.Business.Agent.Util;
using ZLCMS.Commands.User.Util;

namespace ZLCMS.Web.SystemManage.Basics.Shop.Agent
{
    public partial class AgentInterface : System.Web.UI.Page
    {
        protected string UserAccount = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            UserAccount = UserKit.GetUserAccountFailLogin();
            string opt = Request["opt"];
            if (opt == "load_data")
            {
                LoadData();
            }
            if (opt == "add")
            {
                AddNode();
            }
            if (opt == "remove")
            {
                Remove();
            }
            if (opt == "update")
            {
                Update();
            }
        }


        public void Update()
        {
            ShopAgentInfo node = JsonConvert.DeserializeObject<ShopAgentInfo>(Request["data"]);
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                ShopAgentInfo item = session.Get<ShopAgentInfo>(node.Id);
                item.AgentAccount = node.AgentAccount;
                item.Status = node.Status;
                item.BarcodeImg = node.BarcodeImg;
                session.Update(item);
                session.Flush();


                WriteResult(item);
            }
        }


        protected void Remove()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                string nodeRoot = Request["root"];

                session.CreateSQLQuery("update shop_agent_info set status='-1' where agent_prefix like :pf")
                    .SetParameter("pf", "%_" + nodeRoot + "_%")
                    .ExecuteUpdate();

                session.Flush();
                Response.Write("ok");
                Response.End();
            }
        }

        public void AddNode()
        {
            ShopAgentInfo node = JsonConvert.DeserializeObject<ShopAgentInfo>(Request["data"]);
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                int agentCounter = Convert.ToInt32(session.CreateSQLQuery("select count(*) from shop_agent_info  where agent_account=:acc and status='1'")
                        .SetParameter("acc", node.AgentAccount)
                        .UniqueResult());
                if (agentCounter > 0)
                {
                    Response.Write("{\"error\":\"代理人已存在！\"}");
                    Response.End();
                    return;
                }


                //获取sceneid
                Random random = new Random();
                int sceneid = 0, counter = 0;

                ShopAgentInfo agent = null;
                agent = session.CreateQuery("from ShopAgentInfo  where AgentAccount=:acc and status<>'1'")
                        .SetParameter("acc", node.AgentAccount)
                        .UniqueResult<ShopAgentInfo>();
                if (agent == null)
                {
                    agent = new ShopAgentInfo();
                }

                agent.AgentAccount = node.AgentAccount;
                agent.ParentAccount = node.ParentAccount;
                string prefix = session.CreateSQLQuery("select agent_prefix from shop_agent_info  where agent_account=:acc and status='1'")
                        .SetParameter("acc", node.ParentAccount)
                        .UniqueResult<string>();
                if (string.IsNullOrEmpty(prefix))
                {
                    prefix = "_";
                }
                agent.AgentPrefix = prefix + agent.AgentAccount + "_";
                agent.RelationCode = node.RelationCode;
                agent.OperateDate = DateTime.Now;
                agent.Status = "1"; 
                
                bool success = false;
                do
                {
                    sceneid = random.Next(1, 99999);
                    success = Convert.ToInt32(session.CreateSQLQuery("select count(*) from shop_agent_info  where scene_id=:sid")
                        .SetParameter("sid", sceneid)
                        .UniqueResult()) == 0;
                    counter++;
                } while (!success && counter < 20);
                if (success)
                {
                    agent.SceneId = sceneid;
                    BarcodeItem barcode = GetTicket(agent);
                    agent.Url = barcode.Url;
                    agent.Ticket = barcode.Ticket;

                    //string filePath = SaveImage("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + data.Ticket, phone);
                    agent.BarcodeImg = JsonConvert.SerializeObject(new List<SimpleFileInfo>() { new SimpleFileInfo() {
                                            FileId = 0, 
                                            FilePath = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + agent.Ticket,
                                            FileName = "二维码"
                                        } });
                }


                session.SaveOrUpdate(agent);
                session.Flush();

                WriteResult(agent);

            }
        }

        public void WriteResult(ShopAgentInfo data)
        {
            IDictionary result = new Hashtable();
            result["Account"] = data.AgentAccount;
            result["Parent"] = data.ParentAccount;
            result["Id"] = data.Id;
            result["RelationCode"] = data.RelationCode;
            result["Status"] = data.Status;
            result["Ticket"] = data.Ticket;
            result["BarcodeImg"] = data.BarcodeImg;

            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                result["Name"] = session.CreateSQLQuery("select user_name from sys_user_info where user_account=:acc")
                    .SetParameter("acc", data.AgentAccount)
                    .UniqueResult<string>();
                string rCode = session.CreateSQLQuery("select relation_code from shop_agent_info where agent_account=:acc")
                    .SetParameter("acc", data.AgentAccount)
                    .UniqueResult<string>();
                result["long_name"] = AgentUtil.GetRelationName(rCode) + "_" + result["Name"];
            }

            Response.Write(JsonConvert.SerializeObject(result));
            Response.End();
        }

        /// <summary>
        /// 加载产品类型列表
        /// </summary>
        public void LoadData()
        {
            IList<IDictionary> list = new List<IDictionary>();
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                string strSql = @"select b.mobile as Telephone,a.Barcode_Img as BarcodeImg,a.Ticket as Ticket, a.status as Status, a.recid as Id,a.relation_code as RelationCode,a.agent_account as Account,b.user_name as Name,a.parent_account as Parent from shop_agent_info a 
inner join sys_user_info b on a.agent_account=b.user_account where a.status='1'";

                //只能访问自己和下级
                if (!AuthUtil.CheckAuthorization("AGENT_MAN", "ALL"))
                {
                    list = session.CreateSQLQuery(strSql + @" and agent_prefix like :pf")
                    .SetParameter("pf", "%_" + UserKit.GetUserAccount() + "_%")
                    .SetResultTransformer(Transformers.AliasToEntityMap).List<IDictionary>();
                }
                else
                {
                
                    list = session.CreateSQLQuery(strSql).SetResultTransformer(Transformers.AliasToEntityMap).List<IDictionary>();
                }
            }
            foreach (IDictionary item in list)
            {
                item["long_name"] = AgentUtil.GetRelationName(item["RelationCode"] as string) + "_" + item["Name"];
            }
            Response.Write(JsonConvert.SerializeObject(list));
            Response.End();
        }



        protected BarcodeItem GetTicket(ShopAgentInfo data)
        {
            BarcodeItem result = new BarcodeItem();
            string token = WeixinUtil.GetAccessToken(UserKit.GetUserAccountWithoutException());

            WebClient web = new WebClient();
            JToken getUrl = "";
            string posturl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token;
            string jsonStr = string.Format(@"{{
                    ""expire_seconds"": 0, 
                    ""action_name"": ""QR_LIMIT_SCENE"", 
                    ""action_info"": {{
                        ""scene"": {{
                            ""scene_id"": {0}
                        }}
                    }}
                }}", data.SceneId);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(posturl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            byte[] postdata = Encoding.GetEncoding("UTF-8").GetBytes(jsonStr);
            request.ContentLength = postdata.Length;

            Stream newStream = request.GetRequestStream();
            newStream.Write(postdata, 0, postdata.Length);
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();//得到结果

            JObject ticket = JsonConvert.DeserializeObject<JObject>(content);
            if (ticket.TryGetValue("ticket", out getUrl))
            {
                result.Ticket = getUrl.Value<string>();
            }
            if (ticket.TryGetValue("url", out getUrl))
            {
                result.Url = getUrl.Value<string>();
            }
            return result;
        }



        public string SaveImage(string url, string phone)
        {
            string filePath = "";
            try
            {
                string RootPath = System.Web.HttpContext.Current.Server.MapPath("~/");
                string filefolder = "/upload/weixin/" + string.Format("{0:yyyy-MM-dd}/", DateTime.Now.Date);
                if (!System.IO.Directory.Exists(RootPath + filefolder))
                {
                    System.IO.DirectoryInfo info = System.IO.Directory.CreateDirectory(RootPath + filefolder);
                }

                WebRequest request = WebRequest.Create(url);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (System.IO.Stream httpStream = response.GetResponseStream())
                {
                    System.Drawing.Image img = System.Drawing.Image.FromStream(httpStream);
                    Bitmap bmp = new Bitmap(img);
                    Graphics g = Graphics.FromImage(bmp);
                    Font font = new Font("宋体", 15);
                    SolidBrush sbrush = new SolidBrush(Color.Gray);
                    g.DrawString(phone, font, sbrush, new PointF(img.Width - (phone.Length * 15) + 20, img.Height - 25));

                    filePath = filefolder + DateTime.Now.Ticks.ToString();
                    ImageFormat format = ImageFormat.Jpeg;
                    if (img.RawFormat == ImageFormat.Bmp)
                    {
                        filePath += ".bmp";
                        format = ImageFormat.Bmp;
                        bmp.Save(RootPath + filePath, System.Drawing.Imaging.ImageFormat.Bmp);
                    }
                    else if (img.RawFormat == ImageFormat.Gif)
                    {
                        filePath += ".gif";
                        format = ImageFormat.Gif;
                        bmp.Save(RootPath + filePath, System.Drawing.Imaging.ImageFormat.Gif);
                    }
                    else if (img.RawFormat == ImageFormat.Png)
                    {
                        filePath += ".png";
                        format = ImageFormat.Png;
                        bmp.Save(RootPath + filePath, System.Drawing.Imaging.ImageFormat.Png);
                    }
                    else
                    {
                        filePath += ".jpg";
                        format = ImageFormat.Jpeg;
                        bmp.Save(RootPath + filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }

                }

                response.Close();

            }
            catch (Exception ex)
            {
                //MessageBox.Show("文件下载失败错误为" + ex.Message.ToString(), "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            return filePath;

        }
    }
}